define(function(require, exports, module) {
    'use strict';
    
    var rk = require('rk');
    
    
    
    require('core/widgets/input/monthPicker');
    require('core/widgets/input/weekPicker');
    require('oa/js/workreport/asset/statistics/wrStatisticsCtrl');
    var rk_userService = require('core/services/2.0/rk_userService');


    $.widget('rk.wrEditorDialogCtrl', $.rk.oaDialogCtrl, {
        _create: function() {
            var me = this;
            var elem = me.element;

        },
        currentEntity: null,
        isEdit: false,
        _init: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            me.isEdit = !!opt.reportId;

            me._initDatePicker(); //日期范围选择
            me._initRecipient(); //收件人
            me._initCc();
            me._initForm(function(data) {
                me.__initDateTitle(); //编辑
                me.__initStatics(data); //必须等待初始数据，需要currentUnit等参数
                me.__initButtons();
            });
        },
        _initDatePicker: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            if (opt.editorAct != 'create') return;
            var p = $('#timeSelector').parents('tr:first');
            var titleLi = $('#directory_index_container > li');
            var timeSelector = $('#timeSelector');
            if (opt.editorType == 'day') {
                var today = moment();
                timeSelector.val(today.format('YYYY-MM-DD')).datepicker({
                    dateFormat: 'yy-mm-dd',
                    onSelect: function(dateText, inst) {
                        var day = moment(dateText);
                        me._loadStaticsData('day', day);
                        me._initPreviousPlan(day);
                        var _delay_text = opt.delayFlg ? moment(day.add(parseInt(opt.delayDay) - 1, 'days').hour(0).minutes(0).seconds(0).milliseconds(0).toDate().getTime() + parseFloat(opt.delayTime)).format('YYYY-MM-DD HH:mm') : 0;
                        $("span.date-prompt").text(rk.i18n('WORKREPORT_DELAY_TIME_LABEL') + _delay_text);


                    }
                }).attr("readOnly", true);;
            } else if (opt.editorType == 'week') {
                timeSelector.weekPicker({
                    onChange: function(start, end) {
                        me._loadStaticsData('week', start, end);
                        var day = moment(start);
                        me._initPreviousPlan(day);
                        if (opt.delayFlg) {
                            var _delay_text = moment(day.day(parseInt(opt.delayDay) + 4).hour(0).minutes(0).seconds(0).milliseconds(0).toDate().getTime() + parseFloat(opt.delayTime)).format('YYYY-MM-DD HH:mm');
                            !_delay_text || $("span.date-prompt").text(rk.i18n('WORKREPORT_DELAY_TIME_LABEL') + _delay_text);
                        }
                    }
                });
            } else if (opt.editorType == 'month') {
                timeSelector.monthPicker({
                    onChange: function(start, end) {
                        me._loadStaticsData('month', start, end);
                        me._initPreviousPlan(start);
                    }
                });
            }
            p.css('visibility', '');
        },
        _loadStaticsData: function(type, start, end) {
            var me = this;
            var elem = me.element;
            var con = $('#customizingContainer > .detail_sales_data');
            var ownerId = (me.currentEntity ? me.currentEntity.updatedBy : SESSION.user.id);
            con.wrStatisticsCtrl('loadData', type, ownerId, moment(start));
        },
        _initRecipient: function() {
            $("#recipient").rkUser();
        },
        _initCc: function() {
            var ipt = $("#reportUser");
            var title = ipt.attr('title')
            $('#reportUser').multipeopleselector({
                position: {
                    my: 'left top+2'
                },
                //menuWidth: 800,//（可选），菜单宽度，默认是和input同宽
                expandMenuWidth: false //（可选），菜单宽度，是否忽略宽度，由菜单内容自由撑开
            });


            var ipt = $("#reportUser"); // 需重新获取，fcbk会覆盖掉之前的
            var ul = ipt.next('ul');
            ul.attr('title', title);
        },
        _initForm: function(callback) {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            var url = (!me.isEdit ? 'workreport.opencreate' : 'workreport.openupdate');
            var data = (!me.isEdit ? {
                belongTypeId: opt.belongTypeId
            } : {
                reportId: opt.reportId
            });
            elem.find('#customizingContainer').beLoading();
            rk.get(url, data, function(data) {
                if (data && data.status != 0) {
                    var msg = workreportService.getErrorMsg(data.status);
                    if (!msg) {
                        msg = rk.i18n('WORKREPORT_SYSTEM_ERROR');
                    }
                    $('#viewDiv').html('<div class="content_error"><p>' + msg + '</p></div>');
                    return;
                }
                if (data && data.data) {
                    data = data.data;
                    if (data.entity) {
                        opt.belongTypeId = data.entity.type;
                    }
                    var recipient, ccUsers;
                    if (opt.editorAct == 'create') {
                        recipient = data.recipient; //新建时，默认批阅人
                        ccUsers = data.copyUsers; //新建时，默认抄送人
                        var startDate;
                        var timeSelector = $('#timeSelector');
                        if (opt.editorType == 'day') startDate = moment(timeSelector.val());
                        else if (opt.editorType == 'week') startDate = timeSelector.weekPicker('getRange').start;
                        else if (opt.editorType == 'month') startDate = timeSelector.monthPicker('getRange').start;
                        me._initPreviousPlan(startDate);
                    } else if (opt.editorAct == 'edit') {
                        var entity = data.entity;
                        me.currentEntity = data.entity; //cache
                        recipient = entity.recipient;
                        if (entity.copyTo) {
                            var arr = entity.copyTo.split(',');
                            ccUsers = [];
                            for (var i = 0; i < arr.length; i++) {
                                var id = $.trim(arr[i]);
                                ccUsers.push({
                                    uid: id
                                });
                            }
                        }
                    }
                    if (recipient) {
                        var recipientInfo = rk_userService.getUserInfo(recipient);
                        if (recipientInfo) {
                            $("#recipient").rkUser('setUser', recipientInfo.id, recipientInfo.name);
                        }
                    }
                    var dataArray = [];
                    if (ccUsers) { //default cc
                        for (var i = 0; i < ccUsers.length; i++) {
                            var id = ccUsers[i].uid;
                            var info = rk_userService.getUserInfo(id);
                            if (info) {
                                var name = (info.name ? info.name : '');
                                if (name) {
                                    dataArray.push({
                                        label: name,
                                        value: id
                                    });
                                }
                            }
                        }
                        $('#reportUser').multipeopleselector("val", dataArray);
                    }

                    var isDraft = (data.entity && data.entity.draft === '1');
                    if (!isDraft && opt.editorAct == 'edit') {
                        $("#recipient").prop('readonly', true); //非草稿状态，不可编辑审批人
                        $('#reportUser').multipeopleselector('readonly') //非草稿状态，不可编辑抄送人
                    }
                    opt.belongId = data.belongId;
                    if (data.delayFlg) {
                        opt.delayFlg = data.delayFlg;
                        opt.delayDay = data.delayDay;
                        opt.delayTime = data.delayTime;
                    }
                    if (opt.belongId == 25) {
                        var _delay_text = data.delayFlg ? moment(moment().add(parseInt(data.delayDay) - 1, 'days').hour(0).minutes(0).seconds(0).milliseconds(0).toDate().getTime() + parseFloat(data.delayTime)).format('YYYY-MM-DD HH:mm') : 0;
                        !_delay_text || $("span.date-prompt").text(rk.i18n('WORKREPORT_DELAY_TIME_LABEL') + _delay_text);

                    } else if (opt.belongId == 26) {
                        if (data.delayFlg) {
                            var _delay_text = moment(moment().day(parseInt(data.delayDay) + 4).hour(0).minutes(0).seconds(0).milliseconds(0).toDate().getTime() + parseFloat(data.delayTime)).format('YYYY-MM-DD HH:mm');
                            !_delay_text || $("span.date-prompt").text(rk.i18n('WORKREPORT_DELAY_TIME_LABEL') + _delay_text);
                        }

                    }

                    window.currencyUnit = data.currencyUnit;
                    window.recipientId = data.recipient;
                    me._renderAutoForm(data); //自定义字段
                    if (opt.editorAct == 'edit') {
                        if (data.lastPlanItemId) {
                            var lastPlanTextarea = $('[refid=' + data.lastPlanItemId + ']').find("textarea");
                            if (lastPlanTextarea.size() > 0) {
                                var lastReportPlan = entity.lastPlan;
                                if (lastReportPlan == "") {
                                    lastReportPlan = '没有提交上次报告或者上次报告中下次计划未填写';
                                }
                                lastPlanTextarea.val(lastReportPlan);
                                lastPlanTextarea.attr("disabled", true);
                            }
                        }
                    }
                    (callback)(data);
                    rk.repositionDialog();
                }
            });
        },
        _initPreviousPlan: function (dateText) {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            var reportTime = moment(dateText);
            reportTime = reportTime.unix();
            reportTime = reportTime * 1000;


            var optData ={'reportTime':reportTime,'belongTypeId':opt.belongTypeId};
            var url = '/json/oa_workreport/previous-plan.action';
            rk.get(url,optData,function(data){
                if (data && data.status != 0) {
                    var msg = workreportService.getErrorMsg(data.status);
                    if (!msg) {
                        msg = rk.i18n('WORKREPORT_SYSTEM_ERROR');
                    }
                    $('#viewDiv').html('<div class="content_error"><p>' + msg + '</p></div>');
                    return;
                }
                if(data&&data.data){
                    data = data.data;
                    if(data.contentTypeItemId){
                        var contentTextarea = $('[refid='+data.contentTypeItemId+']').find("textarea");
                        if (contentTextarea) {
                            var correlateLastReportPlan = data.correlateLastReportPlan;
                            if (null != correlateLastReportPlan && "" != correlateLastReportPlan ) {
                                correlateLastReportPlan = "来自上次计划：\n" + correlateLastReportPlan+"\n";
                            }
                            contentTextarea.val(correlateLastReportPlan);
                        };
                    }
                    if(data.lastPlanItemId){
                        var lastPlanTextarea = $('[refid=' + data.lastPlanItemId+ ']').find("textarea");
                        if(lastPlanTextarea){
                            var lastReportPlan = data.correlateLastReportPlan;
                            if(lastReportPlan == ""){
                                lastReportPlan = '没有提交上次报告或者上次报告中下次计划未填写';
                            }
                            lastPlanTextarea.val(lastReportPlan);
                            lastPlanTextarea.attr("disabled",true);
                        }
                    }
                }
            });
        },
        _renderAutoForm: function(data) {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            if (data.items) {
                var items = data.items;
                var entity = data.entity;
                var autoformCon = elem.find('#customizingContainer');
                elem.find('#customizingContainer').rkAutoForm({
                    domType: 'div',
                    layoutTagname: 'li',
                    items: data.items, //表单的结构定义
                    data: entity ? entity : {} //（可选），如果是编辑的话，把数据放在这里
                });
                me._renderAttachment(entity);

                var statisticsTpl = require('oa/tmpl/workreport/tpl_workreport_static.tpl');
                autoformCon.prepend(rk.templateText(statisticsTpl));
            }
        },
        _renderAttachment: function(entity) {
            var me = this;
            if (me.isEdit && entity.fileName) {
                me._createReAttachmentLink(entity);
            } else {
                me._createAttachment();
            }
        },
        _createReAttachmentLink: function(entity) {
            entity.name = entity.fileName;
            this.element.find('.fileinput-box').singlefileuploader({
                uploadedFiles: [entity]
            });
            this._createAttachment();
        },
        _createAttachment: function() {
            var me = this;
            var elem = me.element;

            elem.find('.fileinput-box').singlefileuploader({

            });
        },
        __initDateTitle: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            if (opt.editorAct != 'edit') return;
            if (!me.currentEntity.date) return;
            var startMom = moment(parseFloat(me.currentEntity.date));
            var p = $('#timeSelector').parents('tr:first');
            var title = workreportService.getDateTitle(startMom, opt.editorType);
            title = workreportService.getBelongTextByType(opt.editorType) + '&nbsp;' + title;
            $('#timeSelector').parents('td:first').html(title);
            p.css('visibility', '');
        },
        __initStatics: function(data) {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            var timeSelector = $('#timeSelector');

            var con = $('#customizingContainer > .detail_sales_data');

            con.wrStatisticsCtrl({
                belongTypeId: opt.belongTypeId,
                currencyUnit: window.currencyUnit
            });
            var showStatistics = workreportService.shouldShowStatistics(data);

            if (!showStatistics) {
                con.prev().hide();
                con.hide();
                return;
            } else {
                con.prev().show();
                con.show();
            }

            if (opt.editorAct == 'create') {
                if (opt.editorType == 'day') {
                    var today = moment();
                    var day = moment(today);
                    me._loadStaticsData('day', day);
                } else if (opt.editorType == 'week') {
                    var range = timeSelector.weekPicker('getRange');
                    me._loadStaticsData('week', range.start, range.end);
                } else if (opt.editorType == 'month') {
                    var range = timeSelector.monthPicker('getRange');
                    me._loadStaticsData('month', range.start, range.end);
                }
            } else {
                var startMom = moment(parseFloat(me.currentEntity.date));
                var endMom = workreportService.getEndDate(startMom, opt.editorType);
                if (opt.editorType == 'day') {
                    var day = moment(startMom);
                    me._loadStaticsData('day', day);
                } else if (opt.editorType == 'week') {
                    me._loadStaticsData('week', startMom, endMom);
                } else if (opt.editorType == 'month') {
                    me._loadStaticsData('month', startMom, endMom);
                }
            }
        },
        __initButtons: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            var saveBtn = me.getBtn('submit').click(function() {
                me.__save_click();
            });
            //如果是新建或非草稿状态，则不显示draftBtn
            if ((opt.editorAct == 'create') || (opt.editorAct == 'edit' && me.currentEntity.draft == '1')) {
                var draftBtn = me.getBtn('draft').click(function() {
                    me.__draft_click();
                });
                draftBtn.show();
            }
            var cancelBtn = me.getBtn('cancel').click(function() {
                me.__cancel_click();
            });
        },
        __save_click: function() {
            var me = this;
            me.__doSave('0');
        },
        __draft_click: function() {
            var me = this;
            me.__doSave('1');
        },
        __cancel_click: function() {
            rk.closeDialog();
        },
        __doSave: function(draft) {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            var isDraft = (draft == '1');
            var submit = me.__getSaveData(isDraft);
            if (submit) {
                submit["paramMap['draft']"] = draft;
                // var url;
                // if(opt.editorAct == 'edit'){
                //     url = '/json/sns_work_report/update.action?reportId=' + opt.reportId;
                // }else{
                //     url = '/json/sns_work_report/save.action?belongTypeId=' + opt.belongTypeId;
                // }
                var clickedBtn = (draft === '0' ? me.getBtn('submit') : me.getBtn('draft'));
                if (clickedBtn.hasClass('disable')) return; //避免重复点击
                clickedBtn.beLoading();


                var postUrl = (opt.editorAct == 'edit' ? 'workreport.update' : 'workreport.save');
                var postData = (opt.editorAct == 'edit' ? {
                    reportId: opt.reportId
                } : {
                    belongTypeId: opt.belongTypeId
                });
                postData = $.extend(true, postData, submit);

                var hmt_opt_label = 'workreport_' + opt.editorType + '_add';
                //if (window._hmt) {
                //    _hmt.push(['_trackEvent', 'operate', hmt_opt_label, window.SESSION.tenantName]);
                //}
                if (!isDraft && (opt.editorAct != 'edit')) {
                    rk.post('/json/oa_workreport/validate-exist.action', postData, function(data) {
                        if (data.status == '314005') {
                            var warningText = rk.i18n('WORKREPORT_DUPLICATED_CONFIRM', $("#recipient").val());
                            rk.confirm(warningText, {
                                okText: rk.i18n('WORKREPORT_CONTINUE_SUBMIT')
                            }, function() {
                                rk.post(postUrl, postData, function(data) {
                                    if (data && data.status == '0') {
                                        rk.closeDialog();
                                        rk.oa.closeContent();
                                        rk.oa.closeCurtain();
                                        var oaPanel = rk.oa.getPanel();
                                        var minePanel = oaPanel.find('#wr_sub_panel1');
                                        if (minePanel.is(':visible')) {
                                            var tabBtn = minePanel.find('.oa-tab-header > a[belongtypeid="' + opt.belongTypeId + '"]');
                                            tabBtn.click();
                                        }
                                        rk.noticeSuccess(rk.i18n('WORKREPORT_SAVE_SUCCESS'));
                                    } else {
                                        rk.noticeError(rk.i18n('WORKREPORT_SAVE_FAILURE'));
                                        clickedBtn.beLoading('delay');
                                    }
                                })
                                    .done(function() {})
                                    .fail(function() {
                                        rk.noticeError(rk.i18n('WORKREPORT_SAVE_FAILURE') + rk.i18n('WORKREPORT_SYSTEM_NO_RESPONSE'));
                                        clickedBtn.unLoading();
                                    })
                                    .always(function() {
                                        clickedBtn.unLoading();
                                    });
                            });
                        } else if (data.status == 0) {
                            rk.closeDialog();
                            rk.oa.closeContent();
                            rk.oa.closeCurtain();
                            var oaPanel = rk.oa.getPanel();
                            var minePanel = oaPanel.find('#wr_sub_panel1');
                            if (minePanel.is(':visible')) {
                                var tabBtn = minePanel.find('.oa-tab-header > a[belongtypeid="' + opt.belongTypeId + '"]');
                                tabBtn.click();
                            }
                            rk.noticeSuccess(rk.i18n('WORKREPORT_SAVE_SUCCESS'));
                            clickedBtn.beLoading('delay');
                        }
                    }).fail(function() {
                        rk.noticeError(rk.i18n('WORKREPORT_SAVE_FAILURE') + rk.i18n('WORKREPORT_SYSTEM_NO_RESPONSE'));
                        clickedBtn.unLoading();
                    }).always(function() {
                        clickedBtn.unLoading();
                    });
                } else {
                    rk.post(postUrl, postData, function(data) {
                        if (data && data.status == '0') {
                            rk.closeDialog();
                            rk.oa.closeContent();
                            rk.oa.closeCurtain();
                            var oaPanel = rk.oa.getPanel();
                            var minePanel = oaPanel.find('#wr_sub_panel1');
                            if (minePanel.is(':visible')) {
                                var tabBtn = minePanel.find('.oa-tab-header > a[belongtypeid="' + opt.belongTypeId + '"]');
                                tabBtn.click();
                            }
                            rk.noticeSuccess(rk.i18n('WORKREPORT_SAVE_SUCCESS'));
                        } else {
                            rk.noticeError(rk.i18n('WORKREPORT_SAVE_FAILURE'));
                            clickedBtn.beLoading('delay');
                        }
                    })
                        .done(function() {})
                        .fail(function() {
                            rk.noticeError(rk.i18n('WORKREPORT_SAVE_FAILURE') + rk.i18n('WORKREPORT_SYSTEM_NO_RESPONSE'));
                            clickedBtn.unLoading();
                        })
                        .always(function() {
                            clickedBtn.unLoading();
                        });
                }


            }
        },
        __getSaveData: function(isDraft) {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            var recipient = $('#recipient').attr('userid'); //.attr('userid');
            if (!isDraft && !recipient) {
                rk.noticeError(rk.i18n('WORKREPORT_RECIPIENT_INVALID'));
                return;
            }
            if (recipient == SESSION.user.id) {
                rk.noticeError(rk.i18n('WORKREPORT_NOT_SUBMIT_TO_MYSELF'));
                return;
            }
            var value = $('#customizingContainer').rkAutoForm('getData', null, isDraft); //$('#customizingContainer').wrCustomizedCtrl('getValue', isDraft);
            if (!value) {
                if (!isDraft) {
                    return;
                } else {
                    value = [];
                }
            }
            var data = value;
            var ccUsers = [];
            var ccError = false;
            var users = $('#reportUser').multipeopleselector("val");


            $(users).each(function(i, user) {
                var ccid = user.value;
                if (ccid == SESSION.user.id) {
                    rk.noticeError(rk.i18n('WORKREPORT_NOT_COPY_TO_MYSELF'));
                    ccError = true;
                }
                if (ccid == recipient) {
                    rk.noticeError(rk.i18n('WORKREPORT_NOT_COPY_TO_APPROVAL_BY'));
                    ccError = true;
                }
                if (ccError) return false;
                ccUsers.push(ccid)
            });
            if (ccError) return;
            ccUsers = ccUsers.join(','); //fake data！！
            //if(ccUsers){}
            data.push({
                key: 'copyTo',
                val: (ccUsers ? ccUsers : '')
            });
            data.push({
                key: 'recipient',
                val: recipient
            });
            data.push({
                key: 'date', //日期
                val: (function() {
                    if (opt.editorAct == 'edit') return me.currentEntity.date;
                    var timeSelector = $('#timeSelector');
                    var startDate;
                    if (opt.editorType == 'day') startDate = moment(timeSelector.val());
                    else if (opt.editorType == 'week') startDate = timeSelector.weekPicker('getRange').start;
                    else if (opt.editorType == 'month') startDate = timeSelector.monthPicker('getRange').start;
                    if (startDate) {
                        startDate = moment(startDate);
                        startDate.hour(0);
                        startDate.minutes(0);
                        startDate.seconds(0)
                        var ms = startDate.unix();
                        return ms * 1000;
                    }
                })()
            });
            data.push({
                key: 'status',
                val: '1'
            });

            var file = elem.find('.fileinput-box').singlefileuploader('val')[0];
            var fileName = file ? file.name : '';
            var fileUrl = file ? file.url : '';
            data.push({
                key: 'fileName',
                val: fileName
            }, {
                key: 'fileUrl',
                val: fileUrl
            });
            var submit = {};
            for (var i = 0, len = data.length; i < len; i++) {
                var da = data[i];
                //if(da.val){
                submit["paramMap['" + da.key + "']"] = (da.val ? da.val + '' : '');
                // }else{
                //     if(editorType == 'edit'){
                //         submit["paramMap['"+da.key+"']"] = '';//后台要求，批阅人和时间就算空，也要提交
                //     }
                //     if(da.key == 'recipient' || da.key == 'date'){
                //         submit["paramMap['"+da.key+"']"] = '';//后台要求，批阅人和时间就算空，也要提交
                //     }
                // }
            }
            return submit;
        }
    });
});
